package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1. 构造请求参数
        Map paramMap = new HashMap();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");

        //2. 通过HttpClientUtil发送请求，请求微信服务, 获取响应数据，主要是openid
        // GET https://api.weixin.qq.com/sns/jscode2session
        String result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = (String) jsonObject.get("openid");

        //3. 判断openid是否为空，如果为空，代表登录失败，抛出自定义异常
        if (openid == null) {
           throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //4. 查询数据库user表，得到user信息，判断该用户是否为新用户
        User user = userMapper.selectByOpenid(openid);  //user = null xx

        //5. 如果是新用户，需要初始该数据到user表
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .name("u_"+openid.substring(5, 10))
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        //6. 如果不是新用户，直接返回用户信息
        return user;
    }
}
